package cn.zsc.netdisk.service;

import cn.zsc.netdisk.common.AdviseType;
import cn.zsc.netdisk.common.UserInfo;
import cn.zsc.netdisk.mapper.AdviseMapper;
import cn.zsc.netdisk.pojo.Advise;
import cn.zsc.netdisk.pojo.Share;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import reactor.util.annotation.Nullable;

import java.time.LocalDateTime;

/**
 * @author ccying
 * @date 2021/3/7
 */
@Service
@Slf4j
public class AdviseService {
    private final AdviseMapper mapper;

    public AdviseService(AdviseMapper mapper) {
        this.mapper = mapper;
    }

    /**
     * 根据用户账号查找所有通知信息
     * @param offset 分页起始坐标
     * @param row 查询条数
     */
    public Advise[] get(int offset, int row) {
        String uid = UserInfo.getPrincipal();
        log.info(String.format("根据用户账号ID【%s】查找所有通知信息",uid));
        return mapper.findAllByUid(uid, offset, row);
    }

    /**
     * 一键已读通知
     * */
    public void isReadAll() throws Exception {
        log.info("一键已读通知");
        this.mapper.isReadAll();
    }

    /**
     * 读通知
     * @param id 通知ID
     * */
    public void isRead(int id) throws Exception {
        log.info("读通知，消息ID：" + id);
        this.mapper.isRead(id);
    }

    /**
     * 一键清除通知
     * */
    public void deleteAll() throws Exception {
        log.info("一键清除通知");
        this.mapper.deleteAll();
    }

    /**
     * 生成一条分享通知
     * @param uid 接收通知用户ID
     * @param type 通知类型
     * @return 通知信息
     * */
    public Advise to(String uid, AdviseType type, Share share) {
        log.info("生成一条通知");
        Advise advise = new Advise();
        String title = null;
        String content = null;
        LocalDateTime dateTime = LocalDateTime.now();
        int isRead = 0;
        switch (type) {
            case SHARE_FILE: {
                title = "分享文件";
                content = "您在" + dateTime
                        + "分享了文件：" + share.getName()
                        + "，分享链接：" + share.getUrl()
                        + "，密码：" + share.getPassword();
                break;
            } case SHARE_FILE_LISTENER: {
                title = "分享文件过期";
                content = "您的分享文件已过期";
                break;
            } default: {
            }
        }
        advise.setUid(uid);
        advise.setTitle(title);
        advise.setContent(content);
        advise.setCreated(dateTime);
        advise.setIsRead(isRead);
        log.info("通知：" + advise.toString());
        return advise;
    }

    /**
     * 添加一条通知记录
     * */
    public void add(Advise advise) throws Exception {
        log.info("添加一条通知信息记录");
        this.mapper.add(advise);
    }
}
